package com.jacksen.demo.view.surface

import android.content.Context
import android.opengl.GLSurfaceView
import android.opengl.GLU
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

/**
 * Created by admin on 2017/12/23.
 */
class MyGLRender(val context: Context) : GLSurfaceView.Renderer {

    var glBitmap: GLBitmap? = null
    private var width: Int = 0
    private var height: Int = 0
    private var frameSql: Long = 0
    private var viewPortOffset: Int = 0
    private var maxOffset = 400

    init {
        glBitmap = GLBitmap()
    }

    // 每隔16ms 调用一次
    override fun onDrawFrame(gl: GL10) {
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT or GL10.GL_DEPTH_BUFFER_BIT)
        gl.glLoadIdentity()
        gl.glTranslatef(0.0f, 0.0f, -5.0f)

        glBitmap?.draw(gl)
        changeGLViewPort(gl)
    }

    override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
        if (height == 0) {
            this.height = 1
        }
        this.width = width
        gl.glViewport(0, 0, width, height)
        gl.glMatrixMode(GL10.GL_PROJECTION)
        gl.glLoadIdentity()

        GLU.gluPerspective(gl, 45.0f, (width / height).toFloat(), 0.1f, 100.0f)

        gl.glMatrixMode(GL10.GL_MODELVIEW)
        gl.glLoadIdentity()
    }

    override fun onSurfaceCreated(gl: GL10, config: EGLConfig) {
        glBitmap?.loadGLTexture(gl, this.context);

        gl.glEnable(GL10.GL_TEXTURE_2D); // Enable Texture Mapping ( NEW )
        gl.glShadeModel(GL10.GL_SMOOTH); // Enable Smooth Shading
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
        gl.glClearDepthf(1.0f); // Depth Buffer Setup
        gl.glEnable(GL10.GL_DEPTH_TEST); // Enables Depth Testing
        gl.glDepthFunc(GL10.GL_LEQUAL); // The Type Of Depth Testing To Do

        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
    }

    /**
     * 通过改变gl的视角获取
     *
     * @param gl
     */
    private fun changeGLViewPort(gl: GL10) {
        frameSql++
        viewPortOffset++

        if ((frameSql % 100).toInt() == 0) {
            gl.glViewport(0, 0, width, height)
            viewPortOffset = 0
        } else {
            var k = 4
            gl.glViewport(-maxOffset + viewPortOffset * k, -maxOffset
                    + viewPortOffset * k, this.width - viewPortOffset * 2 * k
                    + maxOffset * 2, this.height - viewPortOffset * 2 * k
                    + maxOffset * 2);
        }
    }
}